#include<iostream>
#include<cerrno>
#include<string>
#include<assert.h>
#include<string.h>
#include<unistd.h>
#include<sys/wait.h>
using namespace std;
int main()
{
    int pipefd[2]={0};
    //创建管道
    int n=pipe(pipefd);
    if(n<0)
    {
        cout<<"pipe error,"<<errno<<":"<<strerror(errno)<<endl;
        return 1;
    }
    cout<<"pipefd[0]:"<<pipefd[0]<<endl;
    cout<<"pipefd[1]:"<<pipefd[1]<<endl;

    //创建子进程
    pid_t id=fork();
    assert(id!=-1);
    if(id==0)//子进程
    {
        close(pipefd[0]);
        //开始通讯，结合某种场景
        //const string namestr="hello xiaolu,我是子进程";
        //int cnt=1;
       // char buffer[1024];
       int cnt=0;
        while(true)
        {
            char x='X';
            write(pipefd[1],&x,1);
            cout<<"Cnt:"<<cnt++<<endl;
            sleep(1);
            //break;
            //snprintf(buffer,sizeof buffer, "%s,计数器:,%d,我的PID:%d\n",namestr.c_str(),cnt++,getpid());
            //write(pipefd[1],buffer,strlen(buffer));
            //sleep(1);
        }
        close(pipefd[1]);
        exit(0);
    }
    close(pipefd[1]);

    //关闭不需要的fd
    close(pipefd[1]);

    //开始通讯
    int cnt=0;
    char buffer[1024];
    while(true)
    {
        //sleep(10);
        int n=read(pipefd[0],buffer,sizeof(buffer)-1);
        if(n>0)
        {
            buffer[n]='\0';
            cout<<"我是父进程,child give me message:"<<buffer<<endl;
        }
        else if(n==0)
        {
            cout<<"我是父进程，我读到了了文件末尾"<<endl;
            break;
        }
        else
        {
            cout<<"我是父进程，读取异常"<<endl; 
            break;
        }
        sleep(1);
        if(cnt++>5)break;
    }
    close(pipefd[0]);

    int staus=0;
    waitpid(id,&staus,0);
    cout<<"sig:"<<(staus&0x7F)<<endl;
    sleep(100);
    return 0;

}